package com.ly.upload.web;

import com.ly.bean.Result;
import com.ly.upload.bean.UploadProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadDo {
    @Autowired
    UploadProperties properties;
    @GetMapping("config")
    UploadProperties properties(){
        return properties;
    }

    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file,
                         String type) throws IOException {
        UploadProperties.FileConfig fileConfig = properties.getConfig().get(type);
        String filename = file.getOriginalFilename(); // "1.jpg"
        String prefix = UUID.randomUUID().toString().replaceAll("-", "");
        String suffix = filename.replaceFirst("(.+)(\\.\\w+)","$2");
        filename = prefix + suffix;
        // 如果保存的文件夹不存在,则创建
        File dispath = new File(fileConfig.getDiskpath());
        if(dispath.exists() == false){
            dispath.mkdirs();
        }
        File fileObj = new File(dispath, filename);
        file.transferTo(fileObj);
        String webPath = fileConfig.getWebpath().replaceFirst("\\*{1,2}", filename);
        return new Result(1,"文件上传成功",webPath);
    }

    // TODO 扩展: 多文件上传, 删除文件(提供web路径, 删除对应的磁盘文件, 注销用户, 修改头像)

}

